import { useTranslation } from "@/i18n";
import { FullscreenExitOutlined, FullscreenOutlined } from "@ant-design/icons";
import { useEventListener } from "@nsb/common-tools";
import { ButtonProps } from "antd";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { call_runtime } from "../../../utils/call_runtime";
import { TopBarIconButton } from "./TopBarIconButton";

export async function requestFullscreen(ele: Element): Promise<void> {
  call_runtime('WindowFullscreen')
  if (ele.requestFullscreen)
    return ele.requestFullscreen();
  const fallback = ele as any
  if (fallback.mozRequestFullScreen) {
    fallback.mozRequestFullScreen();
  } else if (fallback.webkitRequestFullscreen) {
    fallback.webkitRequestFullscreen();
  } else if (fallback.msRequestFullscreen) {
    fallback.msRequestFullscreen();
  }
}

export function exitFullscreen() {
  call_runtime('WindowUnfullscreen')
  if (document.exitFullscreen)
    document.exitFullscreen();
  const fallback = document as any
  if (fallback.mozCancelFullScreen) {
    fallback.mozCancelFullScreen();
  } else if (fallback.webkitExitFullscreen) {
    fallback.webkitExitFullscreen();
  } else if (fallback.msExitFullscreen) {
    fallback.msExitFullscreen();
  }
}

export function fullscreenElement(): Element | null {
  const fallback = (document as any)
  return (
    document.fullscreenElement ||
    fallback.mozFullScreenElement ||
    fallback.msFullScreenElement ||
    fallback.webkitFullscreenElement || null
  );
}

export function useFullscreen(ele?: HTMLElement | null) {
  const target = ele || document.body;
  const [is_fullscreen, set_is_fullscreen] = useState(!!fullscreenElement());
  useEventListener(window, 'fullscreenchange', useCallback(() => {
    set_is_fullscreen(!!fullscreenElement())
  }, []))
  useEffect(() => {
    if (is_fullscreen === !!fullscreenElement()) return;
    is_fullscreen ? requestFullscreen(target) : exitFullscreen();
  }, [is_fullscreen, target])
  return { is_fullscreen };
}


export interface IProps extends ButtonProps {
  ele?: HTMLElement | null;
}
export function FullscreenButton(props: IProps) {
  const { t } = useTranslation();
  const { ele, className, onClick, ...remain_props } = props;
  const target = ele || document.body;

  const { is_fullscreen } = useFullscreen(target)
  const title = useMemo(() => is_fullscreen ? t('common.fullscreen_exit') : t('common.fullscreen'), [is_fullscreen])
  const icon = useMemo(() => is_fullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />, [is_fullscreen])

  const on_click = (e: React.MouseEvent<HTMLElement>) => {
    onClick?.(e);
    if (e.isPropagationStopped()) return;
    if (is_fullscreen)
      exitFullscreen()
    else
      requestFullscreen(target)
  }
  return (
    <TopBarIconButton
      className={className}
      title={title}
      onClick={on_click}
      {...remain_props}>
      {icon}
    </TopBarIconButton>
  )
}